<?php
namespace plugin\ky_black\app\admin\controller;

use support\Request;
use support\Response;
use plugin\ky_black\app\admin\model\Order;
use plugin\ky_black\app\admin\model\OrderItem;
use support\Db;

class OrderController extends BaseController
{
    /**
     * 获取订单列表
     * @param Request $request
     * @return Response
     */
    public function list(Request $request): Response
    {
        $query = Order::query();
        
        // 订单号搜索
        if ($orderNo = $request->input('order_no')) {
            $query->where('order_no', 'like', "%{$orderNo}%");
        }
        
        // 会员关键词搜索
        if ($memberKeyword = $request->input('member_keyword')) {
            $query->where(function($q) use ($memberKeyword) {
                $q->where('member_name', 'like', "%{$memberKeyword}%")
                  ->orWhere('member_phone', 'like', "%{$memberKeyword}%");
            });
        }
        
        // 状态筛选
        if ($status = $request->input('status')) {
            $query->where('status', $status);
        }
        
        // 日期范围筛选
        if ($startDate = $request->input('start_date')) {
            $query->where('created_at', '>=', $startDate);
        }
        if ($endDate = $request->input('end_date')) {
            $query->where('created_at', '<=', $endDate);
        }
        
        $list = $query->orderBy('created_at', 'desc')
            ->paginate($request->input('limit', 15));
            
        return $this->success('获取成功', $list);
    }

    /**
     * 获取订单详情
     * @param Request $request
     * @return Response
     */
    public function detail(Request $request): Response
    {
        $orderId = $request->input('order_id');
        
        $order = Order::find($orderId);
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        return $this->success('获取成功', $order);
    }

    /**
     * 取消订单
     * @param Request $request
     * @return Response
     */
    public function cancel(Request $request): Response
    {
        $orderId = $request->input('order_id');
        
        $order = Order::find($orderId);
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        if ($order->status !== 'pending') {
            return $this->error('只能取消待支付订单');
        }
        
        $order->status = 'cancelled';
        $order->cancel_time = date('Y-m-d H:i:s');
        
        if ($order->save()) {
            return $this->success('取消成功');
        }
        return $this->error('取消失败');
    }

    /**
     * 完成订单
     * @param Request $request
     * @return Response
     */
    public function complete(Request $request): Response
    {
        $orderId = $request->input('order_id');
        
        $order = Order::find($orderId);
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        if ($order->status !== 'paid') {
            return $this->error('只能完成已支付订单');
        }
        
        $order->status = 'completed';
        $order->complete_time = date('Y-m-d H:i:s');
        
        if ($order->save()) {
            return $this->success('操作成功');
        }
        return $this->error('操作失败');
    }

    /**
     * 退款
     * @param Request $request
     * @return Response
     */
    public function refund(Request $request): Response
    {
        $orderId = $request->input('order_id');
        
        $order = Order::find($orderId);
        if (!$order) {
            return $this->error('订单不存在');
        }
        
        if (!in_array($order->status, ['paid', 'completed'])) {
            return $this->error('只能退款已支付或已完成的订单');
        }
        
        $order->status = 'refunded';
        $order->refund_time = date('Y-m-d H:i:s');
        
        if ($order->save()) {
            // TODO: 处理实际退款逻辑
            return $this->success('退款成功');
        }
        return $this->error('退款失败');
    }

    /**
     * 更新订单状态
     * @param Request $request
     * @return Response
     */
    public function status(Request $request): Response
    {
        $orderId = $request->input('order_id');
        $status = $request->input('status');
        
        $order = Order::find($orderId);
        if (!$order) {
            return $this->error('订单不存在');
        }

        // 验证状态变更是否合法
        $allowedStatus = ['pending', 'paid', 'completed', 'cancelled', 'refunded'];
        if (!in_array($status, $allowedStatus)) {
            return $this->error('无效的订单状态');
        }

        // 开启事务
        Db::beginTransaction();
        try {
            $order->status = $status;
            $order->save();

            // 更新订单项状态
            $itemStatus = ($status === 'completed' || $status === 'paid') ? 1 : 0;
            OrderItem::where('order_id', $orderId)
                ->update(['status' => $itemStatus]);

            Db::commit();
            return $this->success([], '订单状态更新成功');
        } catch (\Exception $e) {
            Db::rollBack();
            return $this->error('订单状态更新失败：' . $e->getMessage());
        }
    }
}